/*
 * Copyright the original author or authors.
 * 
 * Licensed under the MOZILLA PUBLIC LICENSE, Version 1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.mozilla.org/MPL/MPL-1.1.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 package com.blitscreen.render
{
	import flash.geom.Rectangle;
	import flash.display.BitmapData;
	
	public class BlitSpriteSheet extends BlitSprite
	{
		public var currentFrame : Number;
		public var totalFrames : Number;
		public var startFrame : Number;
		
		protected var _nElapsedTime : Number;
		protected var _nAnimRate : Number;
		
		public function BlitSpriteSheet( bmp : BitmapData, frameSize : Rectangle, rate : Number = 24 )
		{
			super();
			
			bitmap = bmp;
			area.width = frameSize.width;
			area.height = frameSize.height;
			
			totalFrames = Math.ceil( bitmap.width / area.width );
			startFrame = 0;
			currentFrame = 0;
			
			_nAnimRate = Math.floor( 1000 / rate );
			_nElapsedTime = 0;
		}
		
		public function tick( time : Number ) : void
		{
			_nElapsedTime += time;
			
			if( _nElapsedTime > _nAnimRate )
			{
				currentFrame++;
				checkCurrentFrame ();
				_nElapsedTime -= _nAnimRate;
			}			
		}

		protected function checkCurrentFrame () : void
		{			
			if( currentFrame < startFrame ) 
				currentFrame = startFrame;	
			else if( currentFrame >= startFrame + totalFrames )
				currentFrame = startFrame;
				
			area.x = currentFrame * area.width;
		}
		
		override public function toString() : String
		{
			return "[SpriteSheet("+totalFrames+", " + position + ", " + center + ", " + area + ")]";
		}
	}
}